package com.bwie.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbRole;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtil;
import com.bwie.vo.LoginVo;
import com.bwie.vo.RegInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author Lenovo
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2025-07-18 14:01:21
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    TbUserMapper tbUserMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    HttpServletRequest request;

    @Override
    public R sendCode(String mobile) {
        //校验手机号
        boolean mobile1 = Validator.isMobile(mobile);
        if(!mobile1){
            return R.ERROR(400,"手机号格式错误");
        }

        //验证码
        String code = RandomUtil.randomNumbers(4);
        System.out.println("验证码："+code);
        //将验证码存入缓存5分钟
        stringRedisTemplate.opsForValue().set("code-"+mobile,code,5, TimeUnit.MINUTES);

        //发送短信验证码
        MobileMessageUtil.sendMobileMessage(mobile,code);
        return R.OK(code);
    }

    @Override
    public R regUser(RegInfoVo regInfoVo) {
        String key = "code-"+regInfoVo.getUserMobile();
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        //检查缓存
        if(!hasKey){
            return R.ERROR(404,"验证码已过期");
        }
        TbUser tbUser = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserMobile, regInfoVo.getUserMobile())
        );
        if(tbUser != null){
            return R.ERROR(400,"该手机号已经存在");
        }
        String redisCode = stringRedisTemplate.opsForValue().get(key);
        if(!redisCode.equals(regInfoVo.getCode())){
            return R.ERROR(400,"验证码错误");
        }

        TbUser user = new TbUser();
        user.setUserMobile(regInfoVo.getUserMobile());
        //密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(regInfoVo.getUserPass());
        System.out.println("明文密码："+regInfoVo.getUserPass());
        System.out.println("加密后的密码："+encode);
        user.setUserPass(encode);

        user.setUserName("匿名用户");
        user.setCreateBy("系统");
        user.setCreateTime(new Date());
        //注册用户
        tbUserMapper.insert(user);
        return R.OK(user);
    }

    @Override
    public R login(LoginVo loginVo) {
        TbUser tbUser = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserMobile, loginVo.getUserMobile())
        );
        if(tbUser == null){
            return R.ERROR(400,"该手机号不存在");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(loginVo.getUserPass(),tbUser.getUserPass());
        if(!matches){
            return R.ERROR(500,"密码错误");
        }

        //生成JWT
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .claim("userMobile", tbUser.getUserMobile())
                .compact();
        String tokenKey = "token-"+tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(tokenKey,token,60,TimeUnit.MINUTES);

        //获取角色
        List<String> roleList = tbUserMapper.getRoleList(tbUser.getUserId());
        tbUser.setRoles(roleList);

        tbUser.setUserPass(null);
        tbUser.setToken(token);
        return R.OK(tbUser);
    }

    @Override
    public R getMenuTree() {
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登录");
        }
        Integer userId = TokenUtil.userId(token);
        List<TbMenu> tbMenuList = tbUserMapper.getMenuTreeList(userId);

        List<Tree<String>> treeList = TreeUtil.build(tbMenuList, "0", (menu, tree) -> {
            tree.setId(menu.getMenuId() + "");
            tree.setName(menu.getMenuName());
            tree.setParentId(menu.getMenuPid() + "");
            tree.putExtra("path", menu.getMenuPath());
        });

        return R.OK(treeList);
    }

    @Override
    public R getUserInfoById(Integer userId) {
        TbUser tbUser = tbUserMapper.selectById(userId);
        if(tbUser == null){
            return R.ERROR(404,"用户不存在");
        }

        tbUser.setUserPass(null);
        return R.OK(tbUser);
    }
}




